package com.csg.ses.common.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.csg.ses.common.annotation.LoginToken;
import com.csg.ses.common.annotation.PassToken;
import com.csg.ses.common.configuration.SesConfig;
import com.csg.ses.common.utils.RedisUtil;
import com.csg.ses.entity.ses.SysUserLoginEntity;
import com.csg.ses.service.ses.SysUserLoginService;
import com.csg.ses.vo.login.LoginInfo;
import com.csg.ses.vo.login.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 拦截http请求
 * @auther wangjun
 * @date 2020/11/16
 */
@EnableConfigurationProperties(SesConfig.class)
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private SysUserLoginService userLoginService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SesConfig sesConfig;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");   //从 http 请求头中取出 token
        String uri = httpServletRequest.getRequestURI();

        /**
         * 注销登录时，删除存放当前登录人信息的线程信息
         */
        if ("/ses/api/logout".equals(uri)) {
            UserContext.remove();
        }

        /**
         * 如果不是映射到方法直接通过
         */
        if(!(object instanceof HandlerMethod)) {
            return true;
        }

        /**
         * 检查是否有passtoken注释，有则跳过认证
         */
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        /**
         * 检查有没有需要用户权限的注解
         */
        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken userLoginToken = method.getAnnotation(LoginToken.class);
            if (userLoginToken.required()) {
                if (token == null) {
                    throw new RuntimeException("401#无token，请先登录！");
                }

                /**
                 * 获取 token 中的 user login_code
                 */
                String loginCode;
                try {
                    loginCode = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401#无效的token！");
                }

                /**
                 * 验证用户是否存在
                 */
                SysUserLoginEntity user = userLoginService.getByLoginCode(loginCode);
                if (user == null) {
                    throw new RuntimeException("401#用户不存在，请重新登录！");
                }

                /**
                 * 验证redis缓存中的登录信息是否已失效
                 */
                if (!redisUtil.exists(user.getLoginId()) || redisUtil.get(user.getLoginId()) == null) {
                    throw new RuntimeException("401#登录已失效，请重新登录！");
                }

                /**
                 * 验证 token
                 */
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getLoginPwd())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401#token验证不通过！");
                }

                /**
                 * 每一次请求，刷新token有效时间
                 */
                redisUtil.setExpire(user.getLoginId(), sesConfig.getTokenPeriod(), TimeUnit.MINUTES);

                /**
                 * 每一次请求，将当前登录人信息存放到ThreadLocal
                 */
                if (!"ses/api/login".equals(uri)) {
                    UserContext.setUserView(((LoginInfo) redisUtil.get(user.getLoginId())).getUser());
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}